<template>
  <div class="space-y-6">
    <!-- 权限检查 -->
    <div v-if="!canManageTags" class="card">
      <div class="text-center py-8">
        <div class="text-4xl mb-4">🔒</div>
        <h3 class="text-xl font-semibold mb-2">权限不足</h3>
        <p class="text-text-muted">只有管理员可以访问标签管理功能</p>
      </div>
    </div>

    <!-- 标签管理内容 -->
    <div v-else>
      <!-- 标签统计 -->
      <div class="card mb-6">
        <h2 class="text-xl font-semibold mb-4">标签统计</h2>
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div class="bg-background-700 p-4 rounded-lg">
            <div class="text-2xl font-bold text-primary">{{ tagStatistics.total_tags }}</div>
            <div class="text-text-muted">总标签数</div>
          </div>
          <div class="bg-background-700 p-4 rounded-lg">
            <div class="text-2xl font-bold text-primary">{{ tagStatistics.total_categories }}</div>
            <div class="text-text-muted">分类数</div>
          </div>
          <div class="bg-background-700 p-4 rounded-lg">
            <div class="text-2xl font-bold text-primary">{{ tagStatistics.total_usage }}</div>
            <div class="text-text-muted">总使用次数</div>
          </div>
          <div class="bg-background-700 p-4 rounded-lg">
            <div class="text-2xl font-bold text-primary">{{ tagStatistics.active_tags }}</div>
            <div class="text-text-muted">活跃标签</div>
          </div>
        </div>
      </div>

      <!-- 标签分类管理 -->
      <div class="card mb-6">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-xl font-semibold">标签分类</h2>
          <div class="flex items-center gap-2">
            <UiButton 
              @click="toggleCategoryLock" 
              :variant="categoryLocked ? 'secondary' : 'primary'" 
              size="sm"
            >
              {{ categoryLocked ? '🔒' : '🔓' }}
            </UiButton>
            <UiButton 
              @click="showAddCategoryModal = true" 
              variant="primary" 
              size="sm"
              :disabled="categoryLocked"
            >
              添加分类
            </UiButton>
          </div>
        </div>
        
        <div class="space-y-4">
          <div v-for="category in categories" :key="category.id" class="flex items-center justify-between p-4 bg-background-700 rounded-lg">
            <div>
              <h3 class="font-medium">{{ category.display_name }}</h3>
              <p class="text-sm text-text-muted">{{ category.description }}</p>
              <p class="text-xs text-text-muted">名称: {{ category.name }}</p>
            </div>
            <div class="flex items-center gap-2">
              <span class="text-sm text-text-muted">排序: {{ category.sort_order }}</span>
              <UiButton 
                @click="editCategory(category)" 
                variant="ghost" 
                size="sm"
                :disabled="categoryLocked"
              >
                编辑
              </UiButton>
              <UiButton 
                @click="deleteCategory(category.id)" 
                variant="danger" 
                size="sm"
                :disabled="categoryLocked"
              >
                删除
              </UiButton>
            </div>
          </div>
        </div>
      </div>

      <!-- 标签管理 -->
      <div class="card mb-6">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-xl font-semibold">标签管理</h2>
          <UiButton @click="showAddTagModal = true" variant="primary" size="sm">
            添加标签
          </UiButton>
        </div>

        <!-- 分类选择 -->
        <div class="mb-4">
          <UiSelect
            v-model="selectedCategory"
            :options="categoryOptions"
            label="选择分类"
            placeholder="选择要查看的分类"
            @update:model-value="loadTagsForCategory"
          />
        </div>

        <!-- 标签紧凑显示 -->
        <div v-if="selectedCategory && tagsForCategory.length > 0" class="flex flex-wrap gap-2">
          <div 
            v-for="tag in tagsForCategory" 
            :key="tag.id" 
            class="flex items-center gap-2 px-3 py-2 bg-background-700 rounded-lg border border-background-600 hover:border-primary/50 transition-colors"
          >
            <div 
              class="w-3 h-3 rounded-full flex-shrink-0" 
              :style="{ backgroundColor: tag.color }"
            ></div>
            <span class="font-medium text-sm">{{ tag.display_name }}</span>
            <span class="text-xs text-text-muted">({{ tag.usage_count }})</span>
            <div class="flex items-center gap-1 ml-2">
              <UiButton @click="editTag(tag)" variant="ghost" size="sm" class="h-6 px-2 text-xs">
                编辑
              </UiButton>
              <UiButton 
                @click="deleteTag(tag.id)" 
                variant="danger" 
                size="sm"
                class="h-6 px-2 text-xs"
              >
                删除
              </UiButton>
            </div>
          </div>
        </div>
        
        <!-- 空状态 -->
        <div v-else-if="selectedCategory && tagsForCategory.length === 0" class="text-center py-8">
          <div class="text-4xl mb-4">🏷️</div>
          <h3 class="text-lg font-semibold mb-2">暂无标签</h3>
          <p class="text-text-muted">该分类下还没有标签，点击上方按钮添加标签</p>
        </div>
        
        <!-- 未选择分类提示 -->
        <div v-else class="text-center py-8">
          <div class="text-4xl mb-4">📂</div>
          <h3 class="text-lg font-semibold mb-2">请选择分类</h3>
          <p class="text-text-muted">请先选择一个分类来查看和管理标签</p>
        </div>
      </div>
    </div>

    <!-- 添加分类模态框 -->
    <div v-if="showAddCategoryModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-background-800 p-6 rounded-lg w-full max-w-md">
        <h3 class="text-lg font-semibold mb-4">添加标签分类</h3>
        <form @submit.prevent="addCategory" class="space-y-4">
          <UiInput v-model="newCategory.name" label="分类名称" placeholder="例如: genre" required />
          <UiInput v-model="newCategory.display_name" label="显示名称" placeholder="例如: 艺术类型" required />
          <UiTextarea v-model="newCategory.description" label="描述" placeholder="分类的描述信息" :rows="3" />
          <UiNumberInput v-model="newCategory.sort_order" label="排序" placeholder="0" :min="0" :step="1" />
          <div class="flex justify-end gap-2">
            <UiButton @click="showAddCategoryModal = false" variant="secondary">取消</UiButton>
            <UiButton type="submit" variant="primary" :disabled="loading">{{ loading ? '添加中...' : '添加' }}</UiButton>
          </div>
        </form>
      </div>
    </div>

    <!-- 添加标签模态框 -->
    <div v-if="showAddTagModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-background-800 p-6 rounded-lg w-full max-w-md">
        <h3 class="text-lg font-semibold mb-4">添加标签</h3>
        <form @submit.prevent="addTag" class="space-y-4">
          <UiSelect v-model="newTag.category_id" :options="categoryOptions" label="分类" placeholder="选择分类" required />
          <UiInput v-model="newTag.name" label="标签名称" placeholder="例如: fantasy" required />
          <UiInput v-model="newTag.display_name" label="显示名称" placeholder="例如: 奇幻" required />
          <UiTextarea v-model="newTag.description" label="描述" placeholder="标签的描述信息" :rows="3" />
          <div class="flex items-center gap-2">
            <label class="text-sm font-medium">颜色:</label>
            <input v-model="newTag.color" type="color" class="w-12 h-8 rounded border border-background-600" />
          </div>
          <UiNumberInput v-model="newTag.sort_order" label="排序" placeholder="0" :min="0" :step="1" />
          <div class="flex justify-end gap-2">
            <UiButton @click="showAddTagModal = false" variant="secondary">取消</UiButton>
            <UiButton type="submit" variant="primary" :disabled="loading">{{ loading ? '添加中...' : '添加' }}</UiButton>
          </div>
        </form>
      </div>
    </div>

    <!-- 编辑分类模态框 -->
    <div v-if="showEditCategoryModal && editingCategory" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-background-800 p-6 rounded-lg w-full max-w-md">
        <h3 class="text-lg font-semibold mb-4">编辑标签分类</h3>
        <form @submit.prevent="updateCategory" class="space-y-4">
          <UiInput v-model="editingCategory.display_name" label="显示名称" required />
          <UiTextarea v-model="editingCategory.description" label="描述" :rows="3" />
          <UiNumberInput v-model="editingCategory.sort_order" label="排序" :min="0" :step="1" />
          <div class="flex justify-end gap-2">
            <UiButton @click="showEditCategoryModal = false" variant="secondary">取消</UiButton>
            <UiButton type="submit" variant="primary" :disabled="loading">{{ loading ? '更新中...' : '更新' }}</UiButton>
          </div>
        </form>
      </div>
    </div>

    <!-- 编辑标签模态框 -->
    <div v-if="showEditTagModal && editingTag" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-background-800 p-6 rounded-lg w-full max-w-md">
        <h3 class="text-lg font-semibold mb-4">编辑标签</h3>
        <form @submit.prevent="updateTag" class="space-y-4">
          <UiInput v-model="editingTag.display_name" label="显示名称" required />
          <UiTextarea v-model="editingTag.description" label="描述" :rows="3" />
          <div class="flex items-center gap-2">
            <label class="text-sm font-medium">颜色:</label>
            <input v-model="editingTag.color" type="color" class="w-12 h-8 rounded border border-background-600" />
          </div>
          <UiNumberInput v-model="editingTag.sort_order" label="排序" :min="0" :step="1" />
          <div class="flex justify-end gap-2">
            <UiButton @click="showEditTagModal = false" variant="secondary">取消</UiButton>
            <UiButton type="submit" variant="primary" :disabled="loading">{{ loading ? '更新中...' : '更新' }}</UiButton>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue'
import { useTagManagement } from '../../composables/tags'
import { useUserStore } from '../../store/useUserStore'
import { useUiStore } from '../../store/useUiStore'
import { UiButton, UiInput, UiSelect, UiTextarea, UiNumberInput, UiCheckbox } from '../ui'
import type { TagCategory, Tag } from '../../composables/tags'

const {
  loading,
  error,
  categories,
  tags,
  tagStatistics,
  categoryOptions,
  fetchCategories,
  fetchTagsByCategory,
  fetchAllTags,
  fetchTagStatistics,
  createTagCategory,
  updateTagCategory,
  createTag,
  updateTag: updateTagFromComposable,
  deleteTagCategory,
  deleteTag: deleteTagFromComposable
} = useTagManagement()

const userStore = useUserStore()
const { checkUserRole } = userStore
const uiStore = useUiStore()

// 状态
const canManageTags = computed(() => {
  return userStore.isAuthenticated && userStore.currentUserRole === 'admin'
})
const selectedCategory = ref('')
const tagsForCategory = ref<Tag[]>([])
const categoryLocked = ref(true)
const showAddCategoryModal = ref(false)
const showAddTagModal = ref(false)
const showEditCategoryModal = ref(false)
const showEditTagModal = ref(false)

// 编辑状态
const editingCategory = ref<TagCategory | null>(null)
const editingTag = ref<Tag | null>(null)

// 新分类表单
const newCategory = ref({
  name: '',
  display_name: '',
  description: '',
  sort_order: 0
})

// 新标签表单
const newTag = ref({
  category_id: 0,
  name: '',
  display_name: '',
  description: '',
  color: '#3B82F6',
  sort_order: 0
})

// 方法
const toggleCategoryLock = () => {
  categoryLocked.value = !categoryLocked.value
  uiStore.showSuccess(categoryLocked.value ? '分类管理已锁定' : '分类管理已解锁')
}

const loadTagsForCategory = async (categoryId: number) => {
  if (!categoryId) {
    tagsForCategory.value = []
    return
  }

  const category = categories.value.find(cat => cat.id === categoryId)
  if (!category) {
    tagsForCategory.value = []
    return
  }

  await fetchTagsByCategory(category.name)
  tagsForCategory.value = tags.value[category.name] || []
}

const addCategory = async () => {
  try {
    await createTagCategory(newCategory.value)
    uiStore.showSuccess('分类添加成功')
    showAddCategoryModal.value = false
    await Promise.all([fetchAllTags(), fetchTagStatistics()])
    newCategory.value = { name: '', display_name: '', description: '', sort_order: 0 }
  } catch (error) {
    uiStore.showError(error instanceof Error ? error.message : '添加分类失败')
  }
}

const addTag = async () => {
  try {
    if (newTag.value.category_id === 0) {
      uiStore.showError('请选择分类')
      return
    }
    await createTag(newTag.value)
    uiStore.showSuccess('标签添加成功')
    showAddTagModal.value = false
    await Promise.all([fetchAllTags(), fetchTagStatistics()])
    if (selectedCategory.value) {
      await loadTagsForCategory(parseInt(selectedCategory.value))
    }
    newTag.value = { category_id: 0, name: '', display_name: '', description: '', color: '#3B82F6', sort_order: 0 }
  } catch (error) {
    uiStore.showError(error instanceof Error ? error.message : '添加标签失败')
  }
}

const editCategory = (category: TagCategory) => {
  editingCategory.value = { ...category }
  showEditCategoryModal.value = true
}

const editTag = (tag: Tag) => {
  editingTag.value = { ...tag }
  showEditTagModal.value = true
}

const updateCategory = async () => {
  if (!editingCategory.value) return
  try {
    await updateTagCategory(editingCategory.value)
    uiStore.showSuccess('分类更新成功')
    showEditCategoryModal.value = false
    editingCategory.value = null
    await Promise.all([fetchAllTags(), fetchTagStatistics()])
  } catch (error) {
    uiStore.showError(error instanceof Error ? error.message : '更新分类失败')
  }
}

const updateTag = async () => {
  if (!editingTag.value) return
  try {
    await updateTagFromComposable(editingTag.value)
    uiStore.showSuccess('标签更新成功')
    showEditTagModal.value = false
    editingTag.value = null
    await Promise.all([fetchAllTags(), fetchTagStatistics()])
    if (selectedCategory.value) {
      await loadTagsForCategory(parseInt(selectedCategory.value))
    }
  } catch (error) {
    uiStore.showError(error instanceof Error ? error.message : '更新标签失败')
  }
}

const deleteCategory = async (categoryId: number) => {
  if (!confirm('确定要删除这个分类吗？删除后该分类下的所有标签也将被删除。')) return
  try {
    await deleteTagCategory(categoryId)
    uiStore.showSuccess('分类删除成功')
    await Promise.all([fetchAllTags(), fetchTagStatistics()])
    if (selectedCategory.value === categoryId.toString()) {
      selectedCategory.value = ''
      tagsForCategory.value = []
    }
  } catch (error) {
    uiStore.showError(error instanceof Error ? error.message : '删除分类失败')
  }
}

const deleteTag = async (tagId: number) => {
  if (!confirm('确定要删除这个标签吗？')) return
  try {
    await deleteTagFromComposable(tagId)
    uiStore.showSuccess('标签删除成功')
    await Promise.all([fetchAllTags(), fetchTagStatistics()])
    if (selectedCategory.value) {
      await loadTagsForCategory(parseInt(selectedCategory.value))
    }
  } catch (error) {
    uiStore.showError(error instanceof Error ? error.message : '删除标签失败')
  }
}

// 初始化（仅在组件实际挂载时加载）
onMounted(async () => {
  if (userStore.loading) {
    await new Promise<void>(resolve => {
      const unwatch = watch(() => userStore.loading, (newLoading: boolean) => {
        if (!newLoading) { unwatch(); resolve() }
      })
    })
  }

  if (!userStore.isAuthenticated) return
  await checkUserRole()

  if (canManageTags.value) {
    await Promise.all([
      fetchAllTags(),
      fetchTagStatistics()
    ])
  }
})
</script>

